<template>
  <el-drawer
    :visible="drawerVisible"
    @close="cancel"
    v-loading="loading"
      size="60%"
    :wrapperClosable="false"
    style="z-index: 2012"
    append-to-body
  >
    <template v-if="detail">
      <div
        slot="title"
        style="font-size: 28px; font-weight: bold; color: #1a1a1a"
      >
        {{ detail.comeFrom == 1 ? "线下订单详情" : "线上订单详情" }}
      </div>
      <div style="padding: 0 20px 40px">
        <el-tabs v-model="detailActiveTab">
          <el-tab-pane label="基础信息" name="first">
            <el-descriptions :column="1">
              <el-descriptions-item label="门店名称">{{
                shopDetail.shopName || "-"
              }}</el-descriptions-item>
              <el-descriptions-item label="订单号">{{
                detail.orderNo
              }}</el-descriptions-item>
              <el-descriptions-item label="手机号码">{{
                detail.customPhone
              }}</el-descriptions-item>
              <el-descriptions-item label="渠道">
                {{ orderComeFromMap[detail.comeFrom] }}
              </el-descriptions-item>

              <el-descriptions-item label="三方订单号" v-if="detail.mtOrderId">
                {{ detail.mtOrderId }}
              </el-descriptions-item>

              <el-descriptions-item
                label="三方统一订单ID"
                v-if="detail.mtUniOrderId"
              >
                {{ detail.mtUniOrderId }}
              </el-descriptions-item>

              <el-descriptions-item
                label="三方券码号"
                v-if="detail.mtSerialNumbers"
              >
                {{ detail.mtSerialNumbers }}
              </el-descriptions-item>

              <el-descriptions-item
                label="预约时间"
                v-if="detail.comeFrom !== '1'"
              >
                {{ showAppointmentTime }}
              </el-descriptions-item>

              <el-descriptions-item label="商品信息">
                <div>
                  <div v-for="item in detail.orderGoodPoList">
                    {{ item.name }}[{{ item.price }}][{{ item.buyNum }}份]
                  </div>
                </div>
              </el-descriptions-item>
              <el-descriptions-item label="商品总额">
                {{ detail.totalPrice.toFixed(2) }} （元）</el-descriptions-item
              >
              <el-descriptions-item label="订单折扣"
                >{{ detail.discountRatio }}%</el-descriptions-item
              >
              <el-descriptions-item label="订单金额"
                >{{ detail.orderPrice.toFixed(2) }}（元）</el-descriptions-item
              >
              <!-- <el-descriptions-item label="鞋子数量">
                {{ detail.shoeNum }} 双
              </el-descriptions-item> -->

              <el-descriptions-item label="取鞋日期">{{
                detail.mtBeginTime || "-"
              }}</el-descriptions-item>
              <el-descriptions-item label="客户备注">{{
                detail.customerRemark || "-"
              }}</el-descriptions-item>

              <el-descriptions-item label="商家备注">
                <el-input
                  type="textarea"
                  v-model="detail.shopRemark"
                  placeholder="请输入备注"
                  style="width: 300px; margin-right: 10px"
                ></el-input>

                <el-button
                  size="mini"
                  type="primary"
                  :loading="updateShopRemarkLoading"
                  @click="updateShopRemark"
                >
                  更新备注
                </el-button>
              </el-descriptions-item>

              <el-descriptions-item
                label="鞋子信息"
                 labelClassName="hide-label"
                  v-if="detail.shoePoList && detail.shoePoList.length"
              

              >
             

              <TableTongji v-if="drawerVisible" style="flex: 1" :orderId="detail.id" :tableData="detail.shoePoList" :orderDetail="detail" :scene="'detail'"></TableTongji>

              
              </el-descriptions-item>

    
           
            </el-descriptions>

            <div style="display: flex; justify-content: left; margin-top: 30px">
              <template
                v-if="
                  detail.status === 2 &&
                  detail.shoePoList &&
                  !!detail.shoePoList.length
                "
              >
                <el-button style="width: 120px" @click="cancel">取消</el-button>
                <el-button
                  style="width: 120px"
                  type="primary"
                  @click="updateDetail"
                  >确认</el-button
                >
              </template>
              <el-button
                style="width: 120px"
                type="primary"
                @click="printReceipt"
                >打印小票</el-button
              >
            </div>
          </el-tab-pane>
          <template v-if="detail.comeFrom != 1">
            <el-tab-pane label="物流信息" name="second">
              <div
                style="display: flex; justify-content: end; margin-bottom: 20px"
              >
                <el-button
                  type="primary"
                  @click="printTransportPdf"
                  :loading="printTransportLoading"
                  >打印面单</el-button
                >
              </div>
              <el-table
                :data="detail.orderTransportPoList"
                @selection-change="handleLogisticsSelectionChange"
              >
                <el-table-column type="selection" width="55"> </el-table-column>
                <el-table-column prop="type" label="类别"> </el-table-column>
                <el-table-column
                  prop="wayBillCode"
                  label="物流单号"
                  width="150"
                >
                </el-table-column>
                <el-table-column label="快递公司">
                  <template slot-scope="scope"> 京东物流 </template>
                </el-table-column>
                <el-table-column
                  prop="sendFullAddress"
                  label="发件地址"
                  width="200"
                >
                </el-table-column>
                <el-table-column
                  prop="receiverFullAddress"
                  label="收件地址"
                  width="200"
                >
                </el-table-column>
                <el-table-column prop="sendName" label="寄件人" width="200">
                </el-table-column>
                <el-table-column
                  prop="sendMobile"
                  label="寄件人电话"
                  width="200"
                >
                </el-table-column>
                <el-table-column prop="receiverName" label="收件人" width="200">
                </el-table-column>
                <el-table-column
                  prop="receiverMobile"
                  label="收件人电话"
                  width="200"
                >
                </el-table-column>

                <el-table-column label="状态">
                  <template slot-scope="scope">
                    {{ logisticsStatusMap[scope.row.status] }}
                  </template>
                </el-table-column>
                <el-table-column label="预估费用（元）" width="120">
                  <template slot-scope="scope">
                    {{ scope.row.price.toFixed(2) }}
                  </template>
                </el-table-column>
                <el-table-column label="预约时间" width="200">
                  <template slot-scope="scope">
                    {{
                      formatDateTime(
                        Number(scope.row.pickupPromiseTime),
                        "YYYY-MM-DD HH:mm:ss"
                      )
                    }}
                  </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注"> </el-table-column>
                <el-table-column label="操作" width="180" fixed="right">
                  <template slot-scope="scope">
                    <el-button size="mini" @click="showLogisticsLog(scope.row)"
                      >查询</el-button
                    >
                    <!-- <el-button size="mini" @click="print(scope.row.id)"
                      >添加备注</el-button
                    > -->
                    <el-button
                      size="mini"
                      type="primary"
                      v-if="
                        scope.row.type === '取鞋' && scope.row.status <= 390
                      "
                      @click="changeAppointment(scope.row)"
                      >商家改约</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
            <el-tab-pane label="支付信息" name="third">
              <el-descriptions :column="1">
                <el-descriptions-item label="类型"
                  >用户结算</el-descriptions-item
                >

                <el-descriptions-item label="结算方式">
                  券码核销
                </el-descriptions-item>

                <el-descriptions-item label="结算金额">
                  {{
                    detail.settlementPrice
                      ? detail.settlementPrice + "（元）"
                      : "-"
                  }}
                </el-descriptions-item>

                <el-descriptions-item label="优惠金额">
                  -
                </el-descriptions-item>

                <el-descriptions-item label="券码">{{
                  detail.mtSerialNumbers || "-"
                }}</el-descriptions-item>

                <el-descriptions-item label="状态">{{
                  detail.settlementStatus === 2 ? "已核销" : "-"
                }}</el-descriptions-item>

                <el-descriptions-item label="结算时间">{{
                  detail.settlementTime || "-"
                }}</el-descriptions-item>
              </el-descriptions>
            </el-tab-pane>
          </template>
        </el-tabs>
      </div>

      <el-dialog
        title="物流进度"
        :visible.sync="logisticsLogVisible"
        @close="logisticsLogVisible = false"
        width="50%"
        style="z-index: 2013"
        append-to-body
      >
        <el-timeline>
          <el-timeline-item
            v-for="(log, index) in logisticsLogs"
            :key="index"
            :timestamp="log.operationTime"
            icon="el-icon-check"
          >
            {{ log.categoryName }}：{{ log.operationRemark }}
          </el-timeline-item>
        </el-timeline>
      </el-dialog>

      <el-dialog
        title="商家改约"
        :visible.sync="appointmentVisible"
        @close="appointmentVisible = false"
        width="680px"
        style="z-index: 2013"
        append-to-body
      >
        <el-form
          :model="appointmentFormData"
          :rules="appointmentRules"
          ref="appointmentForm"
          label-width="100px"
        >
          <el-form-item label="预约人姓名" prop="reserveName">
            <el-input
              v-model="appointmentFormData.reserveName"
              placeholder="请输入预约人姓名"
              style="width: 100%"
            ></el-input>
          </el-form-item>

          <el-form-item label="预约人地址" prop="reserveAddress">
            <el-input
              v-model="appointmentFormData.reserveAddress"
              placeholder="请输入预约人地址"
            ></el-input>
          </el-form-item>

          <el-form-item label="预约人电话" prop="reservePhone">
            <el-input
              v-model="appointmentFormData.reservePhone"
              placeholder="请输入预约人电话"
            ></el-input>
          </el-form-item>

          <el-form-item label="预约日期" prop="date">
            <el-date-picker
              v-model="appointmentFormData.date"
              style="width: 240px"
              type="date"
              :picker-options="pickerOptions"
              placeholder="预约日期"
            ></el-date-picker>
          </el-form-item>

          <el-form-item
            label="预约时间段"
            prop="time"
            v-if="showAppointmentTimeList"
          >
            <el-button
              class="time-btn"
              v-for="item in showAppointmentTimeList"
              :key="item.label"
              @click="appointmentFormData.time = item.label"
              :type="
                appointmentFormData.time === item.label ? 'primary' : 'default'
              "
            >
              {{ item.label }}
            </el-button>
          </el-form-item>
        </el-form>

        <div style="text-align: right; margin-top: 20px">
          <el-button @click="appointmentVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="appointmentSubmit"
            :loading="appointmentLoading"
            >确认</el-button
          >
        </div>
      </el-dialog>
      <PrintTransport
        ref="printTransport"
        :wayBillCodes="wayBillCodes"
        @success="printTransportLoading = false"
      />
    </template>
  </el-drawer>
</template>

<script>
import { getOrderDetail, updateShoeType } from "@/api/order/index";
import PrintTransport from "@/components/PrintTransport/PrintTransport.vue";
import { getShopDetail } from "@/api/shop/index";
import {
  orderComeFromMap,
  washTypeList,
  IMAGE_OSS_URL,
  logisticsStatusMap,
  shoeStatusMap,
  appointmentTimeList,
} from "@/config/index";
import { getTransportDetail, merchantModify } from "@/api/transport/index";
import { formatDateTime } from "@/utils/formate";
import { getCustomerDetailByPhone } from "@/api/customer/index";
import { updateOrderShopRemark } from "../../../api/order";
import TableTongji from "../inStorage/components/TableTongji.vue";

export default {
  props: ["drawerVisible", "detailId", "productListMap"],
  components: {
    PrintTransport,
    TableTongji
  },
  data() {
    return {
      printTransportLoading: false,
      detailActiveTab: "first",
      detail: false,
      loading: false,

      shopDetail: {},
      washTypeList,
      orderComeFromMap,
      logisticsStatusMap,
      shoeStatusMap,
      multipleSelection: [],

      logisticsLogVisible: false,
      logisticsLogs: [],
      LogisticsSelection: [],
      wayBillCodes: [],

      appointmentVisible: false,
      appointmentLoading: false,
      appointmentTimeList,
      showAppointmentTimeList: null,
      appointmentFormData: {
        reserveName: "",
        reserveAddress: "",
        reservePhone: "",
        date: "",
        time: "",
      },
      pickerOptions: {
        disabledDate(time) {
          const isToDay =
            formatDateTime(time.getTime(), "YYYY-MM-DD") ===
            formatDateTime(Date.now(), "YYYY-MM-DD");
          const nowHours = new Date().getHours();
          return (
            time.getTime() < Date.now() - 8.64e7 || (isToDay && nowHours > 18)
          );
        },
      },
      appointmentRules: {
        reserveName: [
          { required: true, message: "请输入预约人姓名", trigger: "blur" },
        ],
        reserveAddress: [
          { required: true, message: "请输入预约人地址", trigger: "blur" },
        ],
        reservePhone: [
          { required: true, message: "请输入预约人电话", trigger: "blur" },
        ],
        date: [{ required: true, message: "请选择预约日期", trigger: "blur" }],
        time: [
          { required: true, message: "请选择预约时间段", trigger: "blur" },
        ],
      },
      customerDetail: null,

      updateShopRemarkLoading: false,
    };
  },
  computed: {
    showAppointmentTime() {
      const currentTime = this.detail.orderTransportPoList.map((item) => {
        return item.tyee === "取鞋";
      });

      if (currentTime) {
        return formatDateTime(
          currentTime.pickupPromiseTime,
          "YYYY-MM-DD HH:mm:ss"
        );
      }
      return "-";
    },
  },
  watch: {
    drawerVisible(val) {
      if (val === false) {
        this.detail = false;
        this.detailActiveTab = "first";
      } else {
        this.getDetail();
      }
    },
    "appointmentFormData.date"(val) {
      this.appointmentFormData.time = "";
      if (val) {
        const isToDay =
          formatDateTime(val.getTime(), "YYYY-MM-DD") ===
          formatDateTime(Date.now(), "YYYY-MM-DD");
        const nowHours = new Date().getHours();
        this.showAppointmentTimeList = appointmentTimeList.filter((item) => {
          return (isToDay && nowHours < item.startTime) || !isToDay;
        });
      } else {
        this.showAppointmentTimeList = null;
      }
    },
  },
  methods: {
    formatDateTime,
    getDetail() {
      this.loading = true;
      getOrderDetail(this.detailId)
        .then((res) => {
          res.data.shoePoList.forEach((item, index) => {
            item.picture = item.picture
              ? item.picture.split(",").map((key) => {
                   return  {
                    url: IMAGE_OSS_URL + key,
                    status: "success",
                    data: key
                   }
                })
              : [];
            if (res.data.status <= 2) {
              item.washType =
                item.washType ||
                res.data.orderGoodPoList[0].washType ||
                washTypeList[0].value;
            }
            item.index = `${index + 1}/${res.data.shoePoList.length}`;
          });
          res.data.fittingImgList = res.data.fittingImg
            ? res.data.fittingImg.split(",").map((key) => {
                return IMAGE_OSS_URL + key;
              })
            : [];
          this.detail = res.data;
          this.loading = false;
          this.getShopDetail(res.data.shopId);
          this.getCustomerDetail(res.data.customPhone);
        })
        .catch((err) => {
          // console.log(err);
          this.loading = false;
          this.$emit("close");
        });
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    getCustomerDetail(phone) {
      getCustomerDetailByPhone(phone).then((res) => {
        this.customerDetail = res.data;
      });
    },
    getShopDetail(id) {
      getShopDetail(id).then((res) => {
        this.shopDetail = res.data;
      });
    },
    // 打印小票
    printReceipt() {
      this.$emit("printReceipt", this.detail);
    },
    // 打印水洗码
    printWashCode() {
      if (this.multipleSelection.length === 0) {
        this.$message.error("请选择需要打印的水洗码");
        return;
      }
      const hasEmptyType = this.multipleSelection.some(
        (item) => !item.washType
      );
      if (hasEmptyType) {
        this.$message.error("请选择鞋子类型");
        return;
      }
      this.$refs.PrintWashCode.$refs.printBtn.click();
    },
    printWashCodeAll() {
      this.detail.shoePoList.forEach((item) => {
        this.$refs.multipleTable.toggleRowSelection(item);
      });
      this.$nextTick(() => {
        this.printWashCode();
      });
    },
    updateDetail() {
      const params = this.detail.shoePoList.map((item) => {
        return {
          shoeId: item.id,
          shopRemark: this.detail.shopRemark,
          washType: item.washType,
        };
      });
      const emptyType = params.some((item) => !item.washType);
      if (emptyType) {
        this.$message.error("请选择鞋子类型");
        return;
      }
      updateShoeType(params).then(() => {
        this.$message.success("操作成功");
        this.getDetail();
      });
    },
    showLogisticsLog(item) {
      getTransportDetail(item.wayBillCode).then((res) => {
        this.logisticsLogVisible = true;
        this.logisticsLogs = res.data.result.data.traceDetails;
      });
    },
    // 选择物流信息
    handleLogisticsSelectionChange(val) {
      this.LogisticsSelection = val;
    },
    printTransportPdf() {
      if (this.LogisticsSelection.length === 0) {
        this.$message.error("请选择需要打印的物流单");
        return;
      }
      this.printTransportLoading = true;
      this.wayBillCodes = this.LogisticsSelection.map(
        (item) => item.wayBillCode
      );
    },

    cancel() {
      this.$emit("close");
    },
    // 商家改约
    changeAppointment(item) {
      this.appointmentFormData = {
        ...this.appointmentFormData,
        reserveName: item.sendName,
        reserveAddress: item.sendFullAddress,
        reservePhone: item.sendMobile,
        date: "",
        time: "",
      };

      if (
        item.pickupPromiseTime &&
        formatDateTime(item.pickupPromiseTime, "YYYY-MM-DD") ===
          formatDateTime(Date.now(), "YYYY-MM-DD") &&
        new Date(item.pickupPromiseTime).getHours() < 18
      ) {
        this.appointmentFormData.date = new Date(item.pickupPromiseTime);
      } else if (item.pickupPromiseTime > Date.now()) {
        this.appointmentFormData.date = new Date(item.pickupPromiseTime);
        this.appointmentFormData.time = "";
      }

      this.appointmentVisible = true;
    },
    appointmentSubmit() {
      this.$refs.appointmentForm.validate((valid) => {
        if (valid) {
          this.appointmentLoading = true;

          const currentTime = appointmentTimeList.find(
            (item) => item.label === this.appointmentFormData.time
          );

          const bookStartTime = this.appointmentFormData.date.setHours(
            currentTime.startTime
          );
          const bookEndTime = this.appointmentFormData.date.setHours(
            currentTime.endTime
          );

          const params = {
            orderId: this.detail.id,
            reserveName: this.appointmentFormData.reserveName,
            reserveAddress: this.appointmentFormData.reserveAddress,
            reservePhone: this.appointmentFormData.reservePhone,
            bookStartTime,
            bookEndTime,
          };

          merchantModify(params)
            .then(() => {
              this.appointmentLoading = false;
              this.appointmentVisible = false;
              this.$message.success("操作成功");
              this.getDetail();
            })
            .finally(() => {
              this.appointmentLoading = false;
            });
        }
      });
    },
    async updateShopRemark() {
      try {
        this.updateShopRemarkLoading = true;
        await updateOrderShopRemark(this.detail.id, this.detail.shopRemark);
        this.$message.success("更新成功");
      } finally {
        this.updateShopRemarkLoading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.time-btn {
  margin-bottom: 5px;
  &:nth-child(4n + 1) {
    margin-left: 0;
  }
}

::v-deep .hide-label{
    display: none !important;
}
</style>
